<template>
  <view class="chat-container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <text class="iconfont icon-back">←</text>
      </view>
      <view class="title">山海之约小助手</view>
      <view class="more-btn">
        <text class="iconfont icon-more">⋮</text>
      </view>
    </view>
    
    <!-- 聊天内容 -->
    <scroll-view class="chat-content" scroll-y scroll-into-view="msg-bottom" :style="{opacity: 1}" @touchstart="onTouchContent">
      <!-- 时间提示 -->
      <view class="time-tip">今天 {{currentTime}}</view>
      
      <!-- 欢迎消息 -->
      <view class="message-item other">
        <view class="avatar">
          <image src="/static/images/客服.png" mode="aspectFill" class="assistant-avatar"></image>
        </view>
        <view class="message-bubble">
          <view class="message-text">您好！我是山海之约小助手，有什么我可以帮您解答的问题吗？</view>
        </view>
      </view>
      
      <!-- 历史消息 -->
      <block v-for="(item, index) in chatMessages" :key="index">
        <!-- 用户消息 -->
        <view v-if="item.type === 'user'" class="message-item mine">
          <view class="message-bubble">
            <view class="message-text">{{item.content}}</view>
          </view>
          <view class="avatar">
            <image :src="userAvatar || '/static/images/avatar.gif'" mode="aspectFill" class="user-avatar"></image>
          </view>
        </view>
        
        <!-- AI回复 -->
        <view v-else class="message-item other">
          <view class="avatar">
            <image src="/static/images/客服.png" mode="aspectFill" class="assistant-avatar"></image>
          </view>
          <view class="message-bubble">
            <view class="message-text" v-html="formatContent(item.content)"></view>
          </view>
        </view>
      </block>
      
      <!-- 流式输出中 -->
      <view v-if="streaming" class="message-item other">
        <view class="avatar">
          <image src="/static/images/客服.png" mode="aspectFill" class="assistant-avatar"></image>
        </view>
        <view class="message-bubble">
          <view class="message-text" v-html="formatContent(streamingText)"></view>
        </view>
      </view>
      
      <!-- 加载状态 -->
      <view v-if="loading && !streaming" class="message-item other">
        <view class="avatar">
          <image src="/static/images/客服.png" mode="aspectFill" class="assistant-avatar"></image>
        </view>
        <view class="message-bubble loading-bubble">
          <view class="loading-animation">
            <view class="loading-circle"></view>
          </view>
          <text class="loading-text">正在思考中...</text>
          <text v-if="timeoutCountdown > 0" class="timeout-countdown">{{Math.floor(timeoutCountdown / 60)}}:{{(timeoutCountdown % 60).toString().padStart(2, '0')}}</text>
        </view>
      </view>
      
      <!-- 超时提示 -->
      <view v-if="isTimeout" class="timeout-notice">
        <text class="timeout-icon">⏱️</text>
        <text class="timeout-text">客服响应超时，请重新发送问题</text>
        <view class="timeout-btn" @click="resetTimeout">重试</view>
      </view>
      
      <!-- 显示当前问题 -->
      <view v-if="currentQuestion" class="current-question">
        <text>当前问题: {{currentQuestion}}</text>
      </view>
      
      <!-- 底部定位元素 -->
      <view id="msg-bottom" style="height: 20rpx;"></view>
    </scroll-view>
    
    <!-- 猜您想问模块 -->
    <view class="guess-questions">
      <view class="guess-title">
        <view class="question-icon">?</view>
        <text>猜您想问</text>
      </view>
      <view class="question-list">
        <view class="question-item" v-for="(item, index) in questionItems" :key="index" @tap="quickAsk(item)">
          <text>{{item}}</text>
          <text class="arrow">></text>
        </view>
      </view>
    </view>
    
    <!-- 底部输入框 -->
    <view class="input-area">
      <view class="input-wrapper">
        <input type="text" v-model="messageText" placeholder="请输入问题..." confirm-type="send" @confirm="sendMessage" :disabled="loading || streaming" />
      </view>
      <view class="send-btn" @click="sendMessage" :class="{ disabled: loading || streaming || !messageText.trim() }">发送</view>
    </view>
  </view>
</template>

<script>
import { askAI } from '../../api/index.js';
import { getUserInfo } from '../../utils/auth.js';

// 超时时间设置为5分钟（300秒）
const TIMEOUT_DURATION = 300;

export default {
  data() {
    return {
      messageText: '',
      chatMessages: [],
      loading: false,
      streaming: false,
      streamingText: '',
      streamingTimer: null,
      streamingIndex: 0,
      currentTime: '',
      currentQuestion: '',
      scrollTimer: null,
      userInfo: null,
      userAvatar: '',
      timeoutTimer: null,
      timeoutCountdown: 0,
      isTimeout: false,
      questionItems: [
        '怎么查找目的地',
        '旅游产品如何查看',
        '如何预订行程',
        '退款流程咨询',
        '山海之约核心理念',
        '如何搜索景点',
        // '云计算2405A九组小组成员'

      ]
    }
  },
  onLoad() {
    // 设置当前时间
    this.setCurrentTime();
    
    // 获取用户信息
    this.getUserData();
    
    // 确保界面已渲染
    this.$nextTick(() => {
      this.scrollToBottom();
    });
  },
  mounted() {
    // 确保界面在挂载后可见
    this.$nextTick(() => {
      setTimeout(() => {
        this.scrollToBottom();
      }, 300);
    });
  },
  onShow() {
    // 页面显示时滚动到底部
    this.$nextTick(() => {
      setTimeout(() => {
        this.scrollToBottom();
      }, 300);
    });
  },
  onUnload() {
    // 清除定时器
    this.clearAllTimers();
  },
  methods: {
    // 清除所有定时器
    clearAllTimers() {
      if (this.scrollTimer) {
        clearTimeout(this.scrollTimer);
      }
      if (this.streamingTimer) {
        clearInterval(this.streamingTimer);
      }
      if (this.timeoutTimer) {
        clearInterval(this.timeoutTimer);
      }
      if (this.countdownTimer) {
        clearInterval(this.countdownTimer);
      }
    },
    
    // 获取用户信息
    getUserData() {
      try {
        this.userInfo = getUserInfo();
        if (this.userInfo && this.userInfo.avatarUrl) {
          this.userAvatar = this.userInfo.avatarUrl;
        }
        console.log('获取到用户信息:', this.userInfo);
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    },
    
    // 设置当前时间
    setCurrentTime() {
      const now = new Date();
      const hours = now.getHours().toString().padStart(2, '0');
      const minutes = now.getMinutes().toString().padStart(2, '0');
      this.currentTime = `${hours}:${minutes}`;
    },
    
    // 开始超时计时
    startTimeoutTimer() {
      // 先清除之前的定时器
      if (this.timeoutTimer) {
        clearTimeout(this.timeoutTimer);
      }
      if (this.countdownTimer) {
        clearInterval(this.countdownTimer);
      }
      
      // 重置超时状态
      this.isTimeout = false;
      this.timeoutCountdown = TIMEOUT_DURATION;
      
      // 创建超时定时器 - 5分钟后执行
      this.timeoutTimer = setTimeout(() => {
        // 请求超时处理
        if (this.loading) {
          this.handleTimeout();
        }
      }, TIMEOUT_DURATION * 1000);
      
      // 创建倒计时定时器
      this.countdownTimer = setInterval(() => {
        if (this.timeoutCountdown > 0) {
          this.timeoutCountdown--;
        } else {
          clearInterval(this.countdownTimer);
        }
      }, 1000);
    },
    
    // 处理超时情况
    handleTimeout() {
      console.log('AI回答超时');
      
      // 取消加载状态
      this.loading = false;
      this.streaming = false;
      this.isTimeout = true;
      
      // 添加超时消息
      const timeoutMessage = {
        type: 'ai',
        content: '抱歉，回答超时。请重新发送问题或稍后再试。'
      };
      this.chatMessages.push(timeoutMessage);
      
      // 清除定时器
      this.clearAllTimers();
      
      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },
    
    // 重置超时状态
    resetTimeout() {
      this.isTimeout = false;
      this.currentQuestion = '';
      this.scrollToBottom();
    },
    
    // 发送消息
    sendMessage() {
      // 消息内容为空或正在加载时不发送
      if (!this.messageText.trim() || this.loading || this.streaming) return;
      
      // 重置超时状态
      this.isTimeout = false;
      
      // 保存当前问题
      this.currentQuestion = this.messageText.trim();
      console.log('发送问题:', this.currentQuestion);
      
      // 添加用户消息
      const userMessage = {
        type: 'user',
        content: this.messageText.trim()
      };
      this.chatMessages.push(userMessage);
      console.log('添加用户消息到聊天记录, 当前消息数:', this.chatMessages.length);
      
      // 保存消息文本并清空输入框
      const message = this.messageText.trim();
      this.messageText = '';
      
      // 滚动到底部 - 立即显示用户消息
      this.$nextTick(() => {
        this.scrollToBottom();
        
        // 设置加载状态 - 在用户消息显示后执行
        this.loading = true;
        
        // 开始超时计时
        this.startTimeoutTimer();
        
        // 调用AI接口
        setTimeout(() => {
          askAI(message)
            .then(res => {
              console.log('AI回复:', res);
              
              // 如果已经超时，不处理回复
              if (this.isTimeout) {
                return;
              }
              
              // 取消超时计时
              if (this.timeoutTimer) {
                clearTimeout(this.timeoutTimer);
                clearInterval(this.countdownTimer);
                this.timeoutCountdown = 0;
              }
              
              // 取消加载状态
              this.loading = false;
              
              // 开始流式输出
              this.streamingText = '';
              this.streaming = true;
              this.streamAIResponse(res);
            })
            .catch(err => {
              console.error('AI请求错误:', err);
              
              // 如果已经超时，不处理错误
              if (this.isTimeout) {
                return;
              }
              
              // 取消超时计时
              if (this.timeoutTimer) {
                clearTimeout(this.timeoutTimer);
                clearInterval(this.countdownTimer);
                this.timeoutCountdown = 0;
              }
              
              // 添加错误消息
              const errorMessage = {
                type: 'ai',
                content: err.isTimeout 
                  ? '抱歉，服务器响应超时。请稍后再试或换个问题。' 
                  : '抱歉，服务器暂时无法响应，请稍后再试。'
              };
              this.chatMessages.push(errorMessage);
              
              // 取消加载状态
              this.loading = false;
              
              // 滚动到底部
              this.$nextTick(() => {
                this.scrollToBottom();
              });
            });
        }, 300); // 短暂延迟，确保用户看到自己的消息已发送
      });
    },
    
    // 流式输出AI回复
    streamAIResponse(content) {
      console.log('开始流式输出, 内容长度:', content ? content.length : 0);
      if (!content) {
        this.streaming = false;
        return;
      }
      
      const characters = content.split('');
      this.streamingIndex = 0;
      
      if (this.streamingTimer) {
        clearInterval(this.streamingTimer);
      }
      
      this.streamingTimer = setInterval(() => {
        if (this.streamingIndex < characters.length) {
          this.streamingText += characters[this.streamingIndex];
          this.streamingIndex++;
          this.scrollToBottom();
        } else {
          clearInterval(this.streamingTimer);
          this.finishStreaming(content);
        }
      }, 50); // 调整速度
    },
    
    // 完成流式输出
    finishStreaming(content) {
      console.log('完成流式输出，添加AI回复到聊天记录');
      // 添加AI回复到消息列表
      const aiMessage = {
        type: 'ai',
        content: content
      };
      this.chatMessages.push(aiMessage);
      console.log('当前聊天记录数量:', this.chatMessages.length);
      
      // 重置状态
      this.streaming = false;
      this.streamingText = '';
      
      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },
    
    // 清理AI回复内容，去除多余标记
    cleanAIResponse(text) {
      if (!text) return '';
      
      // 去除思考过程
      let cleaned = text.replace(/<think>[\s\S]*?<\/think>/g, '');
      
      // 保留加粗等基本格式
      return cleaned.trim();
    },
    
    // 格式化消息内容，处理加粗等标记
    formatContent(content) {
      if (!content) return '';
      
      // 将markdown风格的加粗转为HTML
      let formatted = content.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
      
      // 处理换行
      formatted = formatted.replace(/\n/g, '<br>');
      
      return formatted;
    },
    
    // 滚动到底部
    scrollToBottom() {
      if (this.scrollTimer) {
        clearTimeout(this.scrollTimer);
      }
      
      this.scrollTimer = setTimeout(() => {
        try {
          uni.createSelectorQuery()
            .in(this)
            .select('#msg-bottom')
            .boundingClientRect(rect => {
              if (rect) {
                uni.pageScrollTo({
                  selector: '#msg-bottom',
                  duration: 100
                });
                console.log('滚动到底部');
              } else {
                console.warn('底部元素不存在，无法滚动');
              }
            })
            .exec();
        } catch (error) {
          console.error('滚动到底部失败:', error);
        }
      }, 50);
    },
    
    // 触摸聊天内容区域
    onTouchContent() {
      // 隐藏键盘
      uni.hideKeyboard();
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },
    
    // 快速提问
    quickAsk(question) {
      this.messageText = question;
      this.sendMessage();
    }
  }
}
</script>

<style lang="scss">
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f0f2f5;
  width: 100%;
  box-sizing: border-box;
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background: #8A2BE2;
  border-bottom: 1px solid #7620cc;
  position: sticky;
  top: 0;
  z-index: 10;
  
  .back-btn, .more-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .iconfont {
      font-size: 40rpx;
      color: #fff;
    }
  }
  
  .title {
    flex: 1;
    text-align: center;
    font-size: 34rpx;
    font-weight: bold;
    padding: 0 20rpx;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    color: #fff;
  }
}

.chat-content {
  flex: 1;
  padding: 20rpx 30rpx;
  overflow-y: auto;
  background-color: #f5f7fa;
  position: relative;
  width: 100%;
  box-sizing: border-box;
  
  .time-tip {
    text-align: center;
    font-size: 24rpx;
    color: #999;
    margin: 30rpx 0;
    background: rgba(0, 0, 0, 0.05);
    display: inline-block;
    padding: 6rpx 16rpx;
    border-radius: 20rpx;
    margin-left: 50%;
    transform: translateX(-50%);
  }
  
  .message-item {
    display: flex;
    margin-bottom: 30rpx;
    
    &.other {
      align-items: flex-start;
      
      .avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        overflow: hidden;
        margin-right: 20rpx;
        background: #e0e0e0;
        flex-shrink: 0;
        
        .assistant-avatar {
          width: 100%;
          height: 100%;
          border-radius: 50%;
        }
        
        .default-avatar {
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          background: #8A2BE2;
          color: #fff;
          font-size: 32rpx;
        }
      }
      
      .message-bubble {
        background: #fff;
        border-radius: 0 16rpx 16rpx 16rpx;
        position: relative;
        box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
        
        &:before {
          content: '';
          position: absolute;
          left: -16rpx;
          top: 20rpx;
          border: 8rpx solid transparent;
          border-right-color: #fff;
        }
      }
      
      .loading-bubble {
        min-width: 200rpx;
        min-height: 100rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 20rpx 30rpx;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
        
        .loading-animation {
          width: 60rpx;
          height: 60rpx;
          position: relative;
          margin-bottom: 16rpx;
          
          .loading-circle {
            width: 100%;
            height: 100%;
            border: 4rpx solid #e0e0e0;
            border-top-color: #8A2BE2;
            border-radius: 50%;
            animation: spin 1s infinite linear;
          }
        }
        
        .loading-text {
          font-size: 28rpx;
          color: #666;
          margin-bottom: 10rpx;
        }
        
        .timeout-countdown {
          font-size: 24rpx;
          color: #ff9800;
          font-weight: bold;
        }
      }
    }
    
    &.mine {
      flex-direction: row-reverse;
      
      .avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        overflow: hidden;
        margin-left: 20rpx;
        background: #e0e0e0;
        flex-shrink: 0;
        
        .user-avatar {
          width: 100%;
          height: 100%;
          border-radius: 50%;
        }
      }
      
      .message-bubble {
        background: #8A2BE2;
        border-radius: 16rpx 0 16rpx 16rpx;
        position: relative;
        box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
        
        .message-text {
          color: #fff;
        }
        
        &:before {
          content: '';
          position: absolute;
          right: -16rpx;
          top: 20rpx;
          border: 8rpx solid transparent;
          border-left-color: #8A2BE2;
        }
      }
    }
    
    .message-bubble {
      max-width: 70%;
      padding: 20rpx 24rpx;
      word-break: break-word;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
      
      .message-text {
        font-size: 32rpx;
        line-height: 1.5;
        word-break: break-all;
        
        strong {
          font-weight: bold;
        }
      }
    }
  }
  
  .timeout-notice {
    margin: 40rpx auto;
    background: rgba(255, 152, 0, 0.1);
    border: 1px solid #ff9800;
    border-radius: 12rpx;
    padding: 20rpx 30rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    max-width: 80%;
    
    .timeout-icon {
      font-size: 48rpx;
      margin-bottom: 16rpx;
    }
    
    .timeout-text {
      font-size: 28rpx;
      color: #ff9800;
      margin-bottom: 20rpx;
      text-align: center;
    }
    
    .timeout-btn {
      background: #ff9800;
      color: #fff;
      font-size: 28rpx;
      padding: 10rpx 30rpx;
      border-radius: 30rpx;
      margin-top: 10rpx;
    }
  }
  
  .current-question {
    text-align: center;
    font-size: 26rpx;
    color: #666;
    background: rgba(0, 0, 0, 0.05);
    padding: 16rpx 20rpx;
    border-radius: 8rpx;
    margin: 30rpx auto;
    max-width: 90%;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  }
}

.input-area {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background: #fff;
  border-top: 1px solid #eee;
  position: sticky;
  bottom: 0;
  z-index: 10;
  
  .input-wrapper {
    flex: 1;
    background: #f5f5f5;
    border-radius: 40rpx;
    padding: 15rpx 30rpx;
    margin-right: 20rpx;
    border: 1px solid #eee;
    
    input {
      width: 100%;
      height: 60rpx;
      font-size: 28rpx;
    }
  }
  
  .send-btn {
    width: 120rpx;
    height: 70rpx;
    background: #8A2BE2;
    color: #fff;
    border-radius: 40rpx;
    font-size: 28rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4rpx 12rpx rgba(138, 43, 226, 0.3);
    
    &.disabled {
      background: #cccccc;
      color: #ffffff;
      box-shadow: none;
    }
  }
}

.guess-questions {
  padding: 20rpx 30rpx;
  background: #fff;
  border-top: 1px solid #eee;
  position: sticky;
  bottom: 0;
  z-index: 10;
  
  .guess-title {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    
    .question-icon {
      width: 36rpx;
      height: 36rpx;
      line-height: 36rpx;
      text-align: center;
      background-color: #ff6b6b;
      color: #fff;
      border-radius: 50%;
      margin-right: 10rpx;
      font-size: 24rpx;
    }
    
    text {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .question-list {
    display: flex;
    flex-direction: column;
    
    .question-item {
      width: 100%;
      padding: 15rpx 20rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #f2f2f2;
      
      text {
        font-size: 28rpx;
        color: #333;
      }
      
      .arrow {
        font-size: 24rpx;
        color: #999;
      }
      
      &:active {
        background-color: #f5f5f5;
      }
    }
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style> 